package com.lzh.rocblogbackend.controller;

import com.lzh.rocblogbackend.common.AjaxResult;
import com.lzh.rocblogbackend.mapper.BlogMapper;
import com.lzh.rocblogbackend.model.Blog;
import com.lzh.rocblogbackend.utils.RedisUtil;
import com.lzh.rocblogbackend.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;

@RestController
public class BlogController {
    @Value("${Service.path}")
    private String servicePath;
    @Value("${Image.path}")
    private String imagePath;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    BlogMapper blogMapper;

    //获取所有博客
    @RequestMapping("/getblog")
    public HashMap<String, Object> getBlog() {
        List<Blog> blogList = blogMapper.getBlog();
        //找到草稿id：21,不让他返回
        for (int i = 0; i < blogList.size(); i++) {
            Blog b = blogList.get(i);
            if (b.getId() == 21) {
                blogList.remove(i);
            }
        }
        return AjaxResult.success(blogList);
    }

    //获取随机五篇博客
    @RequestMapping("/getrandom")
    public HashMap<String, Object> getRandom() {
        //获取所有博客
        List<Blog> blogList = blogMapper.getBlog();
        //如果总博客数不足五篇就直接返回
        if (blogList.size() <= 5) {
            for (int i = 0; i < blogList.size(); i++) {
                //给没有封面的博客写入默认封面
                if (blogList.get(i).getCover() == null || blogList.get(i).getCover().length() == 0) {
                    blogList.get(i).setCover(servicePath + "getimg/default.jpg");
                }
                //标题省略15字
                if (blogList.get(i).getTitle().length() > 15) {
                    blogList.get(i).setTitle(blogList.get(i).getTitle().substring(0, 16) + "...");
                }
                //除去草稿id：21
                if (blogList.get(i).getId() == 21) {
                    blogList.remove(i);
                }
            }
            return AjaxResult.success(blogList);
        } else {
            int num = blogList.size();
            Random random = new Random();
            //用来保存随机到的文章
            List<Blog> randomBlog = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                //随机获取文章加入到randomBlog
                int randomIndex = random.nextInt(num);
                //加入之后从总博客列表删除该篇博客，以免又随机到
                randomBlog.add(blogList.get(randomIndex));
                num--;
                blogList.remove(randomIndex);
                //给没有封面的博客写入默认封面
                if (randomBlog.get(i).getCover() == null || randomBlog.get(i).getCover().length() == 0) {
                    randomBlog.get(i).setCover(servicePath + "getimg/default.jpg");
                }
                //标题省略15字
                if (randomBlog.get(i).getTitle().length() > 15) {
                    randomBlog.get(i).setTitle(randomBlog.get(i).getTitle().substring(0, 16) + "...");
                }
            }
            return AjaxResult.success(randomBlog);
        }
    }

    @RequestMapping("/getbytype")
    public HashMap<String, Object> getByType(String type) {
        List<Blog> blogList = blogMapper.getByType(type);
        return AjaxResult.success(blogList);
    }

    //上传图片
    @RequestMapping("/upload/image")
    public HashMap<String, Object> uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        //获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
        //判断目录是否存在
        File dir = new File(imagePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //重命名文件 防止文件名重复（使用UUID）
        String fileName = UUID.randomUUID().toString() + suffix;
        System.out.println(fileName);

        file.transferTo(new File(imagePath + fileName));

        String[] result = {servicePath + "getimg/" + fileName, "sb", fileName};
        return AjaxResult.success(result);
    }

    //加载图片
    @GetMapping("getimg/{name}")
    public void getImgById(@PathVariable("name") String name, HttpServletResponse response) throws IOException {
        if (name == null || name.length() == 0) {
            return;
        }
        FileInputStream inputStream = new FileInputStream(new File(imagePath + name));
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");

        int len;
        byte[] bytes = new byte[1024];

        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes);
            outputStream.flush();
        }
        outputStream.close();
        outputStream.close();

        return;
    }

    //上传博客
    @RequestMapping("/upload/blog")
    public HashMap<String, Object> uploadBlog(String title, String content, String header, String coverSrc, String type) {
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setHeader(header);
        blog.setCover(coverSrc);
        blog.setCreateTime(TimeUtil.getCurrentTime());
        blog.setLastReviseTime(TimeUtil.getCurrentTime());
        blog.setViewNum(0);
        blog.setType(type);
        int i = blogMapper.postBlog(blog);
        if (i == 1) {
            return AjaxResult.success("发布成功", null);
        } else {
            return AjaxResult.fail(-1, "发布失败");
        }
    }

    //获取单篇文章详情
    @RequestMapping("/getbyid")
    public HashMap<String, Object> getById(int id) {
        return AjaxResult.success(blogMapper.getById(id));
    }

    //
    @RequestMapping("/save/blog")
    public HashMap<String, Object> saveBlog(String title, String content, String header, String coverSrc, String type) {
        //检查是否之前有保存过 保存的博客id为21
        Blog save = blogMapper.getById(21);
        //如果之前保存过就先删除
        if (save != null) {
            int ret = blogMapper.deleteById(21);
            if (ret == 1) {
                System.out.println("删除保存文章成功");
            } else {
                System.out.println("文章删除失败");
            }
        }
        //保存
        Blog blog = new Blog();
        if (title.length() >= 9 && (!(title.substring(title.length() - 9, title.length()).equals("(上次保存的文章)")))) {
            title += "(上次保存的文章)";
        }
        blog.setTitle(title);
        blog.setId(21);
        blog.setContent(content);
        blog.setHeader(header);
        blog.setCover(coverSrc);
        blog.setCreateTime(TimeUtil.getCurrentTime());
        blog.setLastReviseTime(TimeUtil.getCurrentTime());
        blog.setViewNum(0);
        blog.setType(type);
        int i = blogMapper.postBlog(blog);
        if (i == 1) {
            return AjaxResult.success("保存成功", null);
        } else {
            return AjaxResult.fail(-1, "保存失败");
        }
    }

    @RequestMapping("/add/view")
    public void addView(int id) {
        //直接写入数据库
        /*blogMapper.addView(id);*/
        //先缓存到redis
        String filed=String.valueOf(id);
        redisUtil.hincr("blogView",filed,1);
    }

    @RequestMapping("/search")
    public HashMap<String, Object> search(String target) {
        List<Blog> blogList = blogMapper.getBlog();
        List<Blog> result = new ArrayList<>();
        for (Blog blog : blogList) {
            if(blog.getId()==21) {//跳过草稿
                continue;
            }
            String title = blog.getTitle();
            String header = blog.getHeader();
            String content = blog.getContent();
            int index = content.indexOf(target);
            if (index != -1) {
                int begin = index - 10 >= 0 ? index - 10 : 0;
                int end = index + 10 >= content.length() ? content.length() : index + 10;
                blog.setContent(content.substring(begin, end));
                result.add(blog);
                continue;
            } else {
                blog.setContent(content.substring(0, 30));
            }
            if (title.contains(target)) {
                result.add(blog);
            }
        }
        return AjaxResult.success("搜索结果", result);
    }
}
